<?php
/*
 CI Library Cache using Memcached
 Written by: Ciprian Dimofte - 25-12-2009
 */
class Cache {

	function Cache(){
		$this->images = array();
		$this->host = "localhost";
		$this->port = 11211;
		if(count($this->images) > 0){
			$this->expire = 86400*365;
		}else{
			$this->expire = 7200;
		}
		$this->connected_server = array();
		$this->_connect();
	}
	
	function _connect(){
		if(function_exists('memcache_connect')){
			$this->memcache = new Memcache;
			$this->_connect_memcached();
		}
	}

	function _connect_memcached(){
		$error_display = ini_get('display_errors');
		$error_reporting = ini_get('error_reporting');
		if($this->memcache->addServer($this->host, $this->port)) $this->connected_server = $this->host;
		ini_set('error_reporting', $error_reporting);
	}

	function get($key){
		if(empty($this->connected_server)) return false;
		return $this->memcache->get($key);
	}

	function set($key,$data){
		if(empty($this->connected_server)) return false;
		return $this->memcache->set($key, $data, 0, $this->expire);
	}

	function replace($key,$data){
		if(empty($this->connected_server)) return false;
		return $this->memcache->replace($key, $data, 0, $this->expire);
	}

	function delete($key,$when = 0){
		if(empty($this->connected_server)) return false;
		return $this->memcache->delete($key, $when);
	}
	
	function set_images($replace = false){
		foreach($this->images as $image){
			if(!$this->get(md5($image))){
				$this->set(md5($image) , file_get_contents($image));
			}elseif($replace == true){
				$this->replace(md5($image) , file_get_contents($image));
			}
		}
	}

}
?>